using System;
using System.Runtime.InteropServices;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Trentacular.SharePoint.FeatureReceivers;
using Trentacular.SharePoint.Util;

namespace Trentacular.SharePoint.Features.CentralAdminExtensions
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("2d5cec8e-957b-47c3-8546-5837419963c6")]
    public class CentralAdminExtensionsEventReceiver : BaseFeatureReceiver<SPWebApplication>
    {
        public override void FeatureActivated(SPWebApplication webApp, SPFeatureReceiverProperties properties)
        {
            if (!webApp.IsAdministrationWebApplication)
                throw new InvalidOperationException("The Central Administration Extensions Feature can only be activated on the Web Application hosting Central Administration");

            foreach (SPSite site in webApp.Sites)
            {
                var rootWeb = site.RootWeb;
                if (rootWeb.IsCentralAdmin())
                    rootWeb.Features.EnsureActivated(Config.CentralAdminCustomActionsFeatureID);
            }
        }

        public override void FeatureDeactivating(SPWebApplication webApp, SPFeatureReceiverProperties properties)
        {
            foreach (SPSite site in webApp.Sites)
            {
                var rootWeb = site.RootWeb;
                if (rootWeb.IsCentralAdmin())
                    rootWeb.Features.Remove(Config.CentralAdminCustomActionsFeatureID);
            }
        }
    }
}
